package com.archerdu.apply.service.impl;

import java.util.List;

import javax.servlet.http.HttpSession;

import com.archerdu.apply.dao.UserDAO;
import com.archerdu.apply.model.User;
import com.archerdu.apply.service.UserManager;
import com.archerdu.base.dao.IBaseDao;
import com.archerdu.base.exception.BussinessException;
import com.archerdu.base.service.BaseManager;
import com.archerdu.commons.constant.DataConstant;
import com.archerdu.commons.constant.ErrorConstant;
import com.archerdu.commons.util.SHA256;

public class UserManagerImpl extends BaseManager<User, Integer> implements UserManager {

    private static final long serialVersionUID = 9163067090144196614L;

    private UserDAO           userDao;

    public UserDAO getUserDao() {

        return userDao;
    }

    @Override
    public void add(User entity) throws Exception {
        // SHA256加密密码
        User user = new User();
        user.setLoginname(entity.getLoginname());
        if (getAll(user).size() == 0) {
            entity.setPwd(SHA256.encrypt(entity.getPwd()));
            super.add(entity);
        } else {
            throw new BussinessException(ErrorConstant.USER_AREADY_EXISTS);
        }
    }

    public void setUserDao(UserDAO dao) {

        userDao = dao;
    }

    @Override
    protected IBaseDao<User, Integer> getDao() {

        return (IBaseDao<User, Integer>) userDao;
    }

    @Override
    public User checkLogin(User user) {
        user.setPwd(SHA256.encrypt(user.getPwd()));
        List<User> list = getDao().findAll(user);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public void modifyPwd(User user, String oldPassword, HttpSession session) throws Exception {
        if (null != session.getAttribute(DataConstant.SESSION_SYS_USER)) {
            User oldUser = (User) session.getAttribute(DataConstant.SESSION_SYS_USER);
            // 两次密码是否一致
            if (user.getPwd().equals(user.getRepwd())) {
                if (SHA256.encrypt(oldPassword).equals(oldUser.getPwd())) {
                    oldUser.setPwd(SHA256.encrypt(user.getPwd()));
                    getDao().merge(oldUser);
                } else {
                    throw new BussinessException(ErrorConstant.LOGIN_USERNAME_PWD_WRONG);
                }
            } else {
                throw new BussinessException(ErrorConstant.PASSWORD_INDENTIFY_WRONG);
            }
        }
    }
}
